import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store';
import sideRouters from '@/router/sideRouters';

// 解决重复点击导航路由报错
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
}

Vue.use(VueRouter)

// =================================start==============================

// Home路由及其子路由
let HomeRouter = {
    path:'/home',
    name:'Home',
    component:() => import('@/views/admin/home'),
    meta:{title:'首页'},
    children:[
        {
            path:'home_01',
            component:() => import('@/views/admin/home/home_01'),
            meta:{title:'首页01',code:0},
        },
        {
            path:'home_02',
            component:() => import('@/views/admin/home/home_02'),
            meta:{title:'首页02',code:1},
        } 
    ]
}

//User路由及其子路由
let UserRouter = {
    path:'/user',
    name:'User',
    component:() => import('@/views/admin/user'),
    meta:{title:'用户'},
    children:[
        {
            path:'user_01',
            component:() => import('@/views/admin/user/user_01'),
            meta:{title:'用户01',code:0},
        },
        {
            path:'user_02',
            component:() => import('@/views/admin/user/user_02'),
            meta:{title:'用户02',code:1},
        } 
    ]
}

// ============================end===================================

// 主页面
import Login from '@/views/login'
import Admin from '@/views/admin'
// 路由
const routes = [
    {name:'Login',path:'/',component:Login,meta: { title:'登录'}},
    {path:'/admin',redirect:'/home',name:'Admin',component:Admin,children:[HomeRouter,UserRouter]},
]



const router = new VueRouter({
    mode:'history',
    base:process.env.BASE_URL,
    routes
})

// 路由拦截器
router.beforeEach((to, from, next) => {
    console.log(to)
    if(Number.isInteger(to.meta.code)){
        store.commit('setCurrentSideNavIndex',to.meta.code)
    }else if(sideRouters[to.name]){
        store.commit('setCurrentSideNavIndex',0);
        store.commit('setSideRouters',sideRouters[to.name]);
        store.commit('setSideTit',to.meta.title);
        router.push({path:sideRouters[to.name][0].path});
    }
    /* 必须调用 `next` */
    next();
})

export default router